#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>

// 创建子进程， 父进程通过管道向子进程发送“hello，pipe"
int main(int argc, char const *argv[])
{
    /* code */
    int pipefd[2];
    int ret;
    pid_t pid;
    // 创建管道之后， 内核会将文件描述符存储到数组中
    ret = pipe(pipefd);
    if (ret == -1) {
        perror("pipe error \n");
        exit(EXIT_FAILURE);
    }

    // fork 之后， 子进程会复制管道读端文件描述符
    pid = fork();

    if (pid == -1 ) {
        perror("fork error \n");
    } else if (pid == 0) { 
        // 子进程 从管道中读取数据

        close(pipefd[1]); // 关闭写端描述符
        char buf[64] = {0};
        ssize_t rbytes = read(pipefd[0], buf, sizeof(buf));// 这里没有数据时会阻塞
        if (rbytes == -1 ) {
            perror("read error \n");
            close(pipefd[0]);
            exit(EXIT_FAILURE);
        }
        printf("buf: %s\n", buf);
        // 结束之后关闭读
        close(pipefd[0]);
        
    } else if (pid > 0) {
        // 关闭读端描述符
        close(pipefd[0]);
        char buf[] = "hello, pipe";
        ssize_t wbytes = write(pipefd[1], buf, strlen(buf));
        if (wbytes == -1) {
            perror("write error \n");
            wait(NULL);
            close(pipefd[1]);
            exit(EXIT_FAILURE);
        }
        close(pipefd[1]);
        wait(NULL);
    }

    return 0;
}
